var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var joi = require('joi');
var cors = require('cors')
var app = express();
const {task} =  require('./schedule/scheduleTasks')
const schedule = require('node-schedule');
const bodyParser = require('body-parser');
//定时器
//schedule.scheduleJob('*/5 * * * * *', task)
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//全局封装响应的错误或自定义的错误信息
app.use((req, res, next)=>{
  res.cc = (status, err)=>{
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next();
})
//路由之前配置解析 token 的中间件
//解密工具
var jwt = require('express-jwt')
//导入解析的token密钥
var config = require('./schema/config')
// 设置请求体大小限制为 10MB

// app.use(bodyParser.json({ limit: '10000mb' }));
// app.use(bodyParser.urlencoded({ limit: '10000mb', extended: true }));
//路由规则,第一个参数是网络请求的路径，这是中间件
app.use(jwt.expressjwt({secret: config.jwtSecrectKey, algorithms: ["HS256"]}).unless({path:[/^\/(user|admin|noteinfo|costincome)/]}))//
//路由模块


app.use('/user', require('./routes/user'));
app.use('/my', require('./routes/user/info'));
app.use('/my', require('./routes/admin/info'));
app.use('/admin', require('./routes/admin'))
app.use('/admingetuserinfo', require('./routes/admin/user'))
app.use('/adminlandresource', require('./routes/admin/landResource'))
app.use('/adminlandparcel', require('./routes/admin/landParcel'))
app.use('/adminvegetableplot', require('./routes/admin/vegetablePlot'))
app.use('/adminplantingoutput', require('./routes/admin/plantingoutput'))
app.use('/adminplantingcost', require('./routes/admin/plantingcost'))
app.use('/admininfo', require('./routes/admin/admininfo'))
app.use('/noteinfo', require('./routes/note'))
app.use('/adminreview', require('./routes/admin/review'))
app.use('/costincome', require('./routes/user/costincome'))

//数据验证错误的中间件
app.use((err, req, res, next)=>{
  if(err instanceof joi.ValidationError){
    return res.cc('400',err)
  }
  //token解析的失败情况
  //前端需要在请求头 Authorization: [后端生成的token]
  if(err.name === 'UnauthorizedError') return res.cc('身份认证失败')
  res.cc('400',err)//未知的错误
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
